package com.jackstraw.dbtool.service.impl;

import com.jackstraw.dbtool.param.CommonParam;
import com.jackstraw.dbtool.pojo.CreateDBTxtData;
import com.jackstraw.dbtool.pojo.FieldData;
import com.jackstraw.dbtool.pojo.TableData;
import com.jackstraw.dbtool.service.ICreateDBTxtService;
import com.jackstraw.dbtool.utils.DBUtil;
import com.jackstraw.dbtool.utils.MyStringUtil;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 所在包：com.jackstraw.dbtool.service.impl
 * 文件名：
 * 版权：稻草人.
 * 项目：dbtool
 * 功能描述：
 * 修改人：Xinglz
 * 修改时间：2020-01-16 17:36
 */
@Service
public class CreateDBTxtServiceImpl implements ICreateDBTxtService {

    @Override
    public void createDBTxt(CreateDBTxtData createDBTxtData) throws Exception {
        // 获取数据库表列表信息
        List<TableData> tableListInDB = DBUtil.getTableList();
        List<TableData> tableList = new ArrayList<>();
        String selectedTables = createDBTxtData.getSelectedTables();
        // 遍历列表获取各表的字段信息
        for(TableData tableData: tableListInDB) {
            String tableName = tableData.getTableName();
            if (selectedTables.contains(","+tableName+",")) {
                List<FieldData> fieldList = DBUtil.getFieldList(tableName);
                List<String> primaryKeyList = DBUtil.getPrimaryKeyList(tableName);
                tableData.setPrimaryKeyList(primaryKeyList);
                tableData.setFieldList(fieldList);
                tableList.add(tableData);
            }
        }
        // 生成文件
        File file = createFile(createDBTxtData);
        FileWriter fw = new FileWriter(file, true);

        // 生成数据库表字符串
        for (TableData tableData: tableList) {
            String tableStr = createTableStr(tableData);
            fw.append(tableStr);
        }

        // 关闭数据库连接
        if (fw != null)
            fw.close();
    }

    /**
     * 生成数据库表数据文件
     * @param createDBTxtData
     * @return
     */
    private File createFile(CreateDBTxtData createDBTxtData) {
        String basePath = createDBTxtData.getBasePath();
        String fileName = createDBTxtData.getFileName();
        String fileType = createDBTxtData.getFileType();
        File folder = new File(basePath);
        if (!folder.exists())
            folder.mkdirs();
        File file = new File(basePath + "/" + fileName + fileType);
        int i = 0;
        while (file.exists()) {
            file = new File(basePath + "/" + fileName + i + fileType);
        }
        return file;
    }

    /**
     * 生成数据库表字符产
     * @param tableData
     * @return
     */
    private String createTableStr(TableData tableData) {
        String tableDataStr = "";
        // 设置表名
        String tableNameStr = tableData.getTableName() + "(" + handleSymbol(tableData.getRemark()) + ")";
        if (MyStringUtil.isEmpty(tableData.getRemark()))
            System.out.println(CommonParam.LOG_REMARK_PREFIX + "数据表没有表备注：" + tableData.getTableName());
        tableDataStr = "# " + tableNameStr + "\n***\n";
        // 生成表详情
        tableDataStr += "|字段名|字段类型|字段大小|默认值|允许为空|主键|备注|\n";
        tableDataStr += "|:--------:|:----:|:----:|:----:|:------------:|\n";
        List<FieldData> fieldList = tableData.getFieldList();
        String primaryKeyStr = transListToSeperatorStr(tableData.getPrimaryKeyList());
        for (FieldData fieldData: fieldList) {
            String columnName = fieldData.getColumnName();
            String typeName = fieldData.getTypeName();
            String columnSize = fieldData.getColumnSize();
            String defaultValue = fieldData.getDefaultValue();
            String nullAble = fieldData.getNullAble();
            String isPrimaryKey = primaryKeyStr.contains("," + columnName + ",")?"是":"否";
            String remarks = fieldData.getRemarks();
            nullAble = nullAble==null?"Yes":nullAble.equals("1")?"Yes":"No";
            tableDataStr = tableDataStr + "|"+handleSymbol(columnName)+"|"+handleSymbol(typeName)+"|"+handleSymbol(columnSize)+"|"+handleSymbol(defaultValue)+"|"+handleSymbol(nullAble)+"|"+handleSymbol(isPrimaryKey)+"|"+handleSymbol(remarks)+"|\n";
        }
        tableDataStr += "\n\n";
        return tableDataStr;
    }

    /**
     * 替换字符串中的特殊符号
     * @param str
     * @return
     */
    private String handleSymbol(String str) {
        if (MyStringUtil.isEmpty(str))
            return "无";
        String newStr = str.replaceAll(System.lineSeparator(), "<br>");
        newStr = newStr.replaceAll("\r", "<br>");
        newStr = newStr.replaceAll("\n", "<br>");
        newStr = newStr.replaceAll("\r\n", "<br>");
        if(MyStringUtil.isEmpty(newStr)) {
            return "无";
        }
        return newStr;
    }

    /**
     * 将list转换成逗号分隔的字符串
     * @param list
     * @return
     */
    private String transListToSeperatorStr(List<String> list) {
        String str = ",";
        if (list != null) {
            for (String name : list) {
                str = str + name + ",";
            }
        }
        return str;
    }
}
